'use strict';

const Controller = require('egg').Controller;
const BaseController = require('./base');
const { codeRule, decryptRule, phoneRule } = require('../validator/token')
const moment = require("moment");

class TokenController extends BaseController {

    /**
     * 授权登陆
     */
    async authorization() {
        const data = this.ctx.request.body;
        const error = this.app.validator.validate(codeRule, data);
        error && this.ctx.helper.commonErr("code不能为空");
        const res = await this.service.wechat.code2Session(data.code);
        //是否新用户
        const user = await this.service.user.findByWxappOpenid(res.openid);
        if (!user || !user.phone) {
            //先绑定手机，创建用户，特定807为请先去绑定
            this.ctx.helper.commonErr("请先绑定手机号", {returnCode: 807, bean: res.openid});
        }
        //返回token
        const token = await this.service.token.getToken(user.id);
        this.ctx.helper.success({
            bean: token
        })
    }

    /**
     * 解密数据
     */
    async decrypt() {
        const { ctx, app, service, config } = this;
        const data = ctx.request.body;
        const error = app.validator.validate(decryptRule, data);
        error && ctx.helper.commonErr('参数错误', { beans: error })
        const res = await service.wechat.decryptData(data.code, data.encryptedData, data.iv);
        ctx.helper.success({
            beans: res
        })
    }

    /**
     * 绑定手机号
     */
    async bindPhone() {
        const { ctx, app, service } = this;
        const data = ctx.request.body;
        const error = app.validator.validate(phoneRule, data);
        error && ctx.helper.commonErr('参数错误', { beans: error });
        const user = await service.user.bindUser(data);
        const token = await service.token.getToken(user.id);
        ctx.helper.success({
            bean: token
        })
    }

    /**
     * 测试 == 订阅消息
     */
    async send() {
        const userId = await this.userId();
        const user = await this.app.model.User.findByPk(userId, {
            attributes: ['id', 'openid']
        });
        if(!user) {
            this.ctx.helper.commonErr('用户不存在');
        }
        await this.service.wechat.send(user.openid);
        this.ctx.helper.success();
    }

}

module.exports = TokenController;